/**
 * 
 */
package scriptrunner.execution;

import java.io.Serializable;

/**
 * @author Administrator
 * 
 */
public class EvalDivideExpr extends EvaluateExpr implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1970587030694209603L;

	public EvalDivideExpr(EvaluateExpr eeLeft, EvaluateExpr eeRight) {
		this.eeLeft = eeLeft;
		this.eeRight = eeRight;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * scriptrunner.execution.EvaluateExpr#CalculateResult(scriptrunner.execution
	 * .Session)
	 */
	@Override
	public ValueObject CalculateResult(Session se) throws ExecuteErrorException {
		ValueObject left = eeLeft.CalculateResult(se);
		ValueObject right = eeRight.CalculateResult(se);

		if (left instanceof ArithmeticCalculable
				&& right instanceof ArithmeticCalculable) {
			ArithmeticCalculable aLeft = (ArithmeticCalculable) left;
			ArithmeticCalculable aRight = (ArithmeticCalculable) right;

			if (aLeft.getClass() == aRight.getClass())
				return aLeft.Divide(aRight);
			else if (aLeft.ArithmeticTypePreference() < aRight
					.ArithmeticTypePreference()) {
				try {
					ArithmeticCalculable nLeft = (ArithmeticCalculable) aRight
							.getClass().newInstance();
					nLeft.ParseFromString(aLeft.SaveValueToString());
					return nLeft.Divide(aRight);
				} catch (Throwable o) {
					throw new ExecuteErrorException("Divide operation failed");
				}
			} else // (aLeft.ArithmeticTypePreference() >
			// aRight.ArithmeticTypePreference())
			{
				try {
					ArithmeticCalculable nRight = (ArithmeticCalculable) aLeft
							.getClass().newInstance();
					nRight.ParseFromString(aRight.SaveValueToString());
					return aLeft.Divide(nRight);
				} catch (Throwable o) {
					throw new ExecuteErrorException("Divide operation failed");
				}
			}
		} else
			throw new ExecuteErrorException("Divide operation failed");
	}

	protected EvaluateExpr eeLeft, eeRight;
}
